# -*- coding: utf-8 -*-
import random
import time
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from zc_core.dao.sku_dao import SkuDao
from zc_core.spiders.base import BaseSpider
from ctaxccgp.utils.login import SeleniumLogin
from zc_core.util.http_util import retry_request
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter
from ctaxccgp.rules import *


class FullSpider(BaseSpider):
    name = 'full'
    # 常用链接
    index_url = 'https://ctaxccgp.zcygov.cn'
    item_url = 'https://ctaxccgp.zcygov.cn/front/detail/item/{}?timestamp={}'

    custom_settings = {
        'CONCURRENT_REQUESTS': 8,
        'DOWNLOAD_DELAY': 0.11,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 8,
        'CONCURRENT_REQUESTS_PER_IP': 8,
        'DOWNLOADER_MIDDLEWARES': {
            'ctaxccgp.middlewares.ZcyItemMiddleware': 740,
            'zc_core.middlewares.proxy.ProxyMiddleware': 650,
            'zc_core.middlewares.agent.UserAgentMiddleware': 640,
            'ctaxccgp.validator.BizValidator': 500
        }
    }

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)
        # 初始化cookie
        # self.cookies = SeleniumLogin().get_cookies()

    def start_requests(self):
        # cookies = {'SESSION': 'ZjA3NGQ0NTEtYmJlNi00YTI2LWE5ZGYtZWQwNGE2YThiZDAw'}
        # self.session_id = self.cookies.get('SESSION')
        # if not self.cookies:
        #     self.logger.error('init cookie failed...')
        #     return
        # self.logger.info('init cookie: %s', self.cookies)
        #
        yield Request(
            url=self.index_url,
            meta={
                'batchNo': self.batch_no,
                # 'session': self.session_id,
            },
            headers={
                'Connection': 'keep-alive',
                'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
                'X-Requested-With': 'XMLHttpRequest',
                # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400',
                'Accept-Encoding': 'gzip, deflate',
                'Accept-Language': 'zh-CN,zh;q=0.9',
            },
            callback=self.init_cookie,
            errback=self.error_back,
            priority=200,
        )

    def init_cookie(self, response):
        settings = get_project_settings()
        # pool_list = SkuPoolDao().get_sku_pool_list()
        pool_list = SkuDao().get_batch_sku_list(self.batch_no)
        self.logger.info('全量：%s' % (len(pool_list)))
        dist_list = [x for x in pool_list if not self.done_filter.contains(x.get('_id'))]
        self.logger.info('目标：%s' % (len(dist_list)))
        random.shuffle(dist_list)
        for sku in dist_list:
            sku_id = sku.get('_id')
            # 避免无效采集
            offline_time = sku.get('offlineTime', 0)
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue

            yield Request(
                url=self.item_url.format(sku_id, str(int(time.time()))),
                headers={
                    'Connection': 'keep-alive',
                    'Cache-Control': 'max-age=0',
                    'Upgrade-Insecure-Requests': '1',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                },
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'supplierId': sku.get('supplierId'),
                    'supplierName': sku.get('supplierName'),
                    'skuId': sku_id,
                    # 'session': self.session_id,
                },
                callback=self.parse_item_data,
                errback=self.error_back,
            )

    # 处理ItemData
    def parse_item_data(self, response):
        meta = response.meta
        sku_id = meta.get('skuId')
        data = parse_item_data(response)
        if data:
            self.logger.info('商品: [%s]' % sku_id)
            yield data
        else:
            self.logger.error('下架: [%s]' % sku_id)
